package deepbrain.markov;

import deepbrain.simnetwork.structure.WeightedConnectionMatrix;

/**
 * Derived from {@code WeightedConnectionMatrix}, MarkovMatrix represents the
 * Markov transition probability matrix (Mij equals the transition probability
 * from state i to state j). It can also be used as connection matrix of
 * Graphical Markov models.
 * 
 * @author Li Yang
 * @author
 * 
 * @create 2009-8-5
 */
public class MarkovMatrix extends WeightedConnectionMatrix {

	private static final long serialVersionUID = 1704574928644541861L;

	public MarkovMatrix() {
	}

	/**
	 * Validates if this Markov matrix is validated
	 */
	public boolean validate() {
		return validateSign() && validateSum();
	}

	/**
	 * Validates if all elements are non-negative
	 */
	protected boolean validateSign() {
		for (int y = 0; y < getNumOfRows(); y++)
			for (int x = 0; x < getNumOfCols(); x++)
				if (getElement(y, x) != null && getElement(y, x) < 0)
					return false;
		return true;
	}

	/**
	 * Validates if each row's sum is 1.0
	 */
	protected boolean validateSum() {
		for (int y = 0; y < getNumOfRows(); y++) {
			double sum = 0;
			for (int x = 0; x < getNumOfCols(); x++) {
				if (getElement(y, x) != null)
					sum += getElement(y, x);
			}
			if (sum != 1.0)
				return false;
		}
		return true;
	}

}
